package com.itheima.controller;

import com.itheima.service.ShiroService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * Created by Chilly Cui on 2020/9/10.
 */
@Controller
//@RequestMapping("/shiro")
public class ShiroController {

    @Resource
    private ShiroService shiroService;

    @RequestMapping("/testShiroAnnotation")
    public String testShiroAnnotation(HttpSession session) {
        session.setAttribute("shiroSessionKey","value111");
        shiroService.test();
        return "list";
    }

    @RequestMapping("/login")
    public String login(@RequestParam("name") String name,
                        @RequestParam("password") String password,
                        Model model) {
        //1.获取Subject
        Subject subject = SecurityUtils.getSubject();

        //2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);

        //3.执行登录方法
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            System.out.println("登录失败: " + e.getMessage());
            model.addAttribute("msg", e.getMessage());
            return "login";
        }

        return "list";
    }

    @RequestMapping("/logout")
    public String login() {
        return "/login";
    }

    @RequestMapping("/admin")
    public String toAdmin() {
        return "/admin";
    }

    @RequestMapping("/user")
    public String toUser() {
        return "/user";
    }
}
